import socket
import time
import cv2
import numpy

import socketserver 
# from socketserver import SocketServer
import time  
  
HOST = '0.0.0.0'  
PORT = 8002

server_addr =(HOST, PORT)


def recvall(sock, count):
    buf = b''#buf是一个byte类型
    while count:
        #接受TCP套接字的数据。数据以字符串形式返回，count指定要接收的最大数据量.
        newbuf = sock.recv(count)
        if not newbuf: return None
        buf += newbuf
        count -= len(newbuf)
    return buf
  
class MyHandler(socketserver.BaseRequestHandler):
    
    def handle(self):

        win_name = "%s_%s"%(self.client_address[0], self.client_address[1])

        while True:

            try:
                start = time.time()#用于计算帧率信息                
                length = recvall(self.request, 16)               #获得图片文件的长度,16代表获取长度
                stringData = recvall(self.request, int(length))  #根据获得的文件长度，获取图片文件                
                data = numpy.frombuffer(stringData, numpy.uint8) #将获取到的字符流数据转换成1维数组
                decimg = cv2.imdecode(data, cv2.IMREAD_COLOR) # image decode
                #将帧率信息回传，主要目的是测试可以双向通信
                end = time.time()
                seconds = end - start
                fps  = 1/seconds
                self.request.send(bytes(str(int(fps)),encoding='utf-8'))
                
            except ConnectionError as e:
                print("Error: ", e)
                break

            try:
                # Processing Image Data                
                cv2.imshow(win_name,decimg) # image show

                k = cv2.waitKey(1) & 0xff
                
                if k == 27:
                    break

            except Exception as e:
                print("Data Procesing Error", e)
                continue
        
        cv2.destroyWindow('SERVER')

#s = socketserver.ThreadingTCPServer((HOST,PORT), MyHandler)  
s = socketserver.TCPServer((HOST,PORT), MyHandler)  
s.serve_forever()
